import React, { useEffect, useState, useCallback } from 'react'
import Taro, { useShareAppMessage, useShareTimeline, useDidShow } from '@tarojs/taro'
import { View, Button } from '@tarojs/components'
import { useSelector, useDispatch } from 'react-redux'
import { AtModal, AtModalHeader, AtModalContent, AtModalAction } from 'taro-ui'
import {
  SpScreenAd,
  SpPage,
  SpSearch,
  SpRecommend,
  SpPrivacyModal,
  SpTabbar,
  SpCouponPackage
} from '@/components'
import api from '@/api'
import {
  isWeixin,
  isEmpty,
  getDistributorId,
  VERSION_STANDARD,
  VERSION_PLATFORM,
  classNames,
  getCurrentPageRouteParams,
  resolveStringifyParams
} from '@/utils'
import entryLaunch from '@/utils/entryLaunch'
import { updateLocation } from '@/store/slices/user'
import { updateShopInfo } from '@/store/slices/shop'
import { useImmer } from 'use-immer'
import { useLogin, useNavigation } from '@/hooks'
import GoodsList from './home/wgts/goods-list'
import HomeWgts from './home/comps/home-wgts'
import CompAddTip from './home/comps/comp-addtip'
import CompFloatMenu from './home/comps/comp-floatmenu'

import './home/index.scss'

const MCompAddTip = React.memo(CompAddTip)
const MSpPrivacyModal = React.memo(SpPrivacyModal)

const initialState = {
  wgts: [],
  showBackToTop: false,
  loading: true,
  isOpened: false
}

function Home() {
  const [state, setState] = useImmer(initialState)
  const [likeList, setLikeList] = useImmer([])

  const { initState, openRecommend, openLocation, openStore, appName } = useSelector(
    (state) => state.sys
  )
  const fetchLocationTiem = Taro.getStorageSync('fetchLocationTiem')
  const newFetchLocationTiem = Date.now()

  const { isLogin, login, checkPolicyChange } = useLogin({
    policyUpdateHook: (isUpdate) => {
      if (isUpdate) {
        setPolicyModal(true)
      } else {
        // if (
        //   !location &&
        //   ((VERSION_STANDARD && openLocation == 1) || VERSION_PLATFORM) &&
        //   newFetchLocationTiem - fetchLocationTiem > 172800000
        // ) {
        //   setState((draft) => {
        //     draft.isOpened = true
        //   })
        // }
      }
    }
  })

  const [policyModal, setPolicyModal] = useState(false)
  const showAdv = useSelector((member) => member.user.showAdv)
  const { location } = useSelector((state) => state.user)
  const { openScanQrcode } = useSelector((state) => state.sys)
  const { setNavigationBarTitle } = useNavigation()

  const { wgts, loading, isOpened } = state

  const dispatch = useDispatch()

  useEffect(() => {
    if (initState) {
      init()
    }
  }, [initState])

  useDidShow(() => {
    if (process.env.APP_BUILD_TARGET == 'app') {
      getAppversionCode()
    }
    setNavigationBarTitle(appName)
    // 检查隐私协议是否变更或同意
    checkPolicyChange()
  })

  const init = async () => {
    // if (!VERSION_STANDARD) {
    await fetchWgts()
    // }
  }
  const getAppversionCode = async () => {
    isAndroid()
    const res = await Taro.request({
      url: 'https://admin.mimijishi.com/api/appUpdate?name=app.client'
    })
    const result = res.data.data
    if (Taro.getEnv() == 'SAPP') {
      const verCode = plus.runtime.versionCode //客户端的版本号
      // alert(`${verCode},${plus.runtime.version},${plus.runtime.innerVersion}`)
      if (result.code > verCode) {
        showUpdate(result)
      } else {
      }
    }
  }

  const showUpdate = (result) => {
    Taro.showModal({
      title: '已经有新版本了哟~',
      content: result.content,
      confirmText: '去更新',
      success: function (res) {
        if (res.confirm) {
          //去下载
          const isAndr = isAndroid()
          if (isAndr) {
            downloadNewVersion(result.url)
          }
        }
      }
    })
  }
  const isAndroid = () => {
    var u = navigator.userAgent
    var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1
    var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)

    // if (isAndroid) {
    //   alert('Android')
    // }else if(isiOS){
    //   alert('iOS')
    // }else{
    //   alert('啥都不是')
    // }
    return isAndroid
  }
  const downloadNewVersion = (url) => {
    var dtask = plus.downloader.createDownload(
      url,
      {
        filename: '_downloads/'
      },
      function (d, status) {
        // 下载完成
        if (status == 200) {
          plus.runtime.install(
            d.filename,
            {
              force: false
            },
            function () {
              //进行重新启动;
              // plus.runtime.restart();
            },
            (e) => {
            }
          )
        } else {
          plus.nativeUI.alert('下载升级包失败，请手动去站点下载安装，错误码: ' + status)
        }
      }
    )
    dtask.start()
  }

  const fetchWgts = async () => {
    const { config } = await api.shop.getShopTemplate({
      distributor_id: getDistributorId()
    })
    setState((draft) => {
      draft.wgts = config
      draft.loading = false
    })
    // fetchLikeList()
  }

  const fetchLikeList = async () => {
    if (openRecommend == 1) {
      const query = {
        page: 1,
        pageSize: 30
      }
      const { list } = await api.cart.likeList(query)
      setLikeList(list)
    }
  }

  // 定位
  const fetchLocation = async () => {
    try {
      const res = await entryLaunch.getCurrentAddressInfo()
      dispatch(updateLocation(res))
    } catch (e) {
      // 定位失败，获取默认店铺
    }
    setState((draft) => {
      draft.isOpened = false
    })
    if (VERSION_STANDARD) {
      fetchStoreInfo(location)
    }
  }
  const handleConfirmModal = useCallback(async () => {
    setPolicyModal(false)
    // if (
    //   !location &&
    //   ((VERSION_STANDARD && openLocation == 1) || VERSION_PLATFORM) &&
    //   newFetchLocationTiem - fetchLocationTiem > 172800000
    // ) {
    //   setState((draft) => {
    //     draft.isOpened = true
    //   })
    // }
  }, [])

  useShareAppMessage(async (res) => {
    const { title, imageUrl } = await api.wx.shareSetting({ shareindex: 'index' })
    const params = getCurrentPageRouteParams()
    const { userId } = Taro.getStorageSync('userinfo')
    params.shareUserId = userId
    params.company_id = process.env.APP_COMPANY_ID
    const path = `/pages/index?${isEmpty(params) ? `` : `${resolveStringifyParams(params)}`}`
    return {
      title: title,
      imageUrl: imageUrl,
      path
    }
  })

  useShareTimeline(async (res) => {
    const { title, imageUrl } = await api.wx.shareSetting({ shareindex: 'index' })
    const params = getCurrentPageRouteParams()
    const { userId } = Taro.getStorageSync('userinfo')
    params.shareUserId = userId
    params.company_id = process.env.APP_COMPANY_ID
    return {
      title: title,
      imageUrl: imageUrl,
      query: resolveStringifyParams(params)
    }
  })

  const fetchStoreInfo = async (location) => {
    let params = {
      distributor_id: getDistributorId() // 如果店铺id和经纬度都传会根据哪个去定位传参
    }
    if (openLocation == 1 && location) {
      const { lat, lng } = location
      params.lat = lat
      params.lng = lng
      // params.distributor_id = undefined
    }
    const res = await api.shop.getShop(params)
    dispatch(updateShopInfo(res))
    await fetchWgts()
  }

  const searchComp = wgts.find((wgt) => wgt.name == 'search')
  const pageData = wgts.find((wgt) => wgt.name == 'page')
  let filterWgts = []
  if (searchComp && searchComp.config.fixTop) {
    filterWgts = wgts.filter((wgt) => wgt.name !== 'search' && wgt.name != 'page')
  } else {
    filterWgts = wgts.filter((wgt) => wgt.name != 'page')
  }

  const fixedTop = searchComp && searchComp.config.fixTop

  const isShowHomeHeader =
    VERSION_PLATFORM ||
    (openScanQrcode == 1 && isWeixin) ||
    (VERSION_STANDARD && openStore && openLocation == 1) ||
    fixedTop


  return (
    <SpPage
      className='page-index'
      scrollToTopBtn
      // renderNavigation={renderNavigation()}
      pageConfig={pageData?.base}
      renderFloat={wgts.length > 0 && <CompFloatMenu />}
      renderFooter={<SpTabbar />}
      loading={loading}
    >
      <AtModal isOpened={isOpened}>
        <AtModalHeader>位置权限授权</AtModalHeader>
        <AtModalContent>
          用于在你搜索商品、搜店铺,向你推荐最近的商品或店铺,以提升体验,或帮助你在发布信息中展示位置,不授权该权限不影响app正常使用
        </AtModalContent>
        <AtModalAction>
          <Button
            onClick={() => {
              setState((draft) => {
                draft.isOpened = false
                Taro.setStorage({
                  key: 'fetchLocationTiem',
                  data: Date.now()
                })
              })
            }}
          >
            关闭
          </Button>
          <Button style='color: #21B991;margin-top:0;' onClick={fetchLocation}>
            继续
          </Button>
        </AtModalAction>
      </AtModal>
      <View
        className={classNames('home-body', {
          'has-home-header': isShowHomeHeader && isWeixin
        })}
      >
        {isShowHomeHeader && fixedTop && <SpSearch info={searchComp} />}
        <HomeWgts wgts={filterWgts} onLoad={fetchLikeList}>
          {/* 猜你喜欢 */}
          <SpRecommend className='recommend-block' info={likeList} />
          <GoodsList goodsSort='4' />
        </HomeWgts>
      </View>

      {/* 小程序搜藏提示 */}
      {isWeixin && <MCompAddTip />}

      {/* 开屏广告 */}
      {isWeixin && !showAdv && <SpScreenAd />}

      {/* 隐私政策 */}
      <MSpPrivacyModal
        open={policyModal}
        onCancel={() => {
          setPolicyModal(false)
        }}
        onConfirm={handleConfirmModal}
      />

      {/* 优惠券包 */}
      {VERSION_STANDARD && <SpCouponPackage />}
    </SpPage>
  )
}

export default Home
